package com.capgemini.expense.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import com.capgemini.expense.model.ExpenseForm;
import com.capgemini.expense.model.Status;

public class ExpenseFormDao extends JPADao<ExpenseForm> {

	public ExpenseFormDao() {
		this.managedEntitiesType = ExpenseForm.class;
	}

	@SuppressWarnings("unchecked")
	public List<ExpenseForm> getByEmployeeId(Long id) {
		EntityManager em = EntityManagerFactoryHolder.get().createEntityManager();
		try {
			Query q = em.createQuery("SELECT e FROM ExpenseForm e WHERE e.employeeId = :employeeId");
			q.setParameter("employeeId", id);
			List<ExpenseForm> result = q.getResultList();
			if (result == null || result.size() == 0) {
				return null;
			} else {
				return result;
			}
		} finally {
			em.close();
		}
	}
	
	public void deleteByEmployeeId(Long id) {
		EntityManager em = EntityManagerFactoryHolder.get().createEntityManager();
		try {
			Query q = em.createQuery("DELETE FROM ExpenseForm e WHERE e.employeeId = :employeeId");
			q.setParameter("employeeId", id);
			q.executeUpdate();
		} finally {
			em.close();
		}
	}
	
	public void deleteAll() {
		EntityManager em = EntityManagerFactoryHolder.get().createEntityManager();
		try {
			Query q = em.createQuery("DELETE FROM ExpenseForm e");
			q.executeUpdate();
		} finally {
			em.close();
		}
	}

	public void saveExpenseForm(ExpenseForm form, Long employeeId) {

		form.setEmployeeId(employeeId);
		form.setStatusId(Status.NEW.getId());
		saveOrUpdate(form);
	}

	public void saveState(Long expenseFormId, int statusId) {
		ExpenseForm form = get(expenseFormId);
		if (form == null) {
			throw new RuntimeException("form with id " + expenseFormId + " not found");
		}
		form.setStatusId(statusId);
		saveOrUpdate(form);
	}
}
